<template>
  <div>
    <Row :gutter="10">
      <Col>
        <Card>
          <div class="live_wrapper clearfix" style="margin-top: 10px">
            <Button type="primary"
                    @click.stop="exportData()"
                    style="float:right; width: 80px;height: 34px;font-size: 14px; margin-left: 10px">导出
            </Button>
            <Button type="primary"
                    style="float:right;width:90px;height: 34px;margin-left: 10px;font-size: 14px;"
                    @click="add"
                    v-if="permissionList.indexOf('shop-add') !== -1">添加
            </Button>
            <Input v-model="filter.name"
                   @on-search="search"
                   search
                   enter-button="搜索"
                   placeholder="请输入门店名称"
                   style="display:inline-table; width: 210px;" />
          </div>

          <p class="admin_title">全部门店</p>

          <Row class="margin-top-10 table_pattern table_pattern2">
            <Table style="width: calc(100vw - 256px - 36px - 32px)"
                   :loading="loading"
                   :columns="columns"
                   :data="list"></Table>
          </Row>
          <Row class="margin-top-10">
            <Page :total="pagenation.totalPage"
                  :page-size="pagenation.perPage"
                  :current="pagenation.currentPage"
                  show-elevator
                  show-total
                  @on-change="change"></Page>
          </Row>
        </Card>
      </Col>
    </Row>

    <Modal v-model="showEditModal"
           :title="formValidate.id == 0 ? '添加' : '编辑'"
           width="40%"
           :mask-closable="false"
           class="public_modal_header edit_modal">
      <Form :model="formValidate"
            ref="formValidate"
            :label-width="120"
            style="width: 90%;margin: 0 auto;padding: 25px 0 10px;">
        <FormItem label="名称" prop="name" class="label_required">
          <Input v-model="formValidate.name" placeholder="请输入门店名称" />
        </FormItem>
        <FormItem label="门店简称" prop="sub_name" class="label_required">
          <Input v-model="formValidate.sub_name" placeholder="例：新北1店，白云2店" maxlength="6" />
        </FormItem>
        <FormItem label="logo" prop="logo" class="label_required label_required2">
          <div class="clearfix live_cover">
            <div style="float: left;margin-right: 18px;">
              <template>
                <div class="demo-upload-list" v-if="formValidate.logo">
                  <img :src="formValidate.logo" style='width:100px; height:100px;object-fit: cover;'>
                  <div class="demo-upload-list-cover">
                    <Icon type="ios-eye-outline" @click.native="handleView(formValidate.logo)"></Icon>
                    <Icon type="ios-trash-outline" @click.native="handleRemove()"></Icon>
                  </div>
                </div>
                <div v-if="!formValidate.logo">
                  <div class="no_pic"><img src="../../assets/images/expo/pic2.png" alt="" width="24" /></div>
                </div>
              </template>
            </div>
            <Upload ref="upload"
                    :max-size="1024"
                    :show-upload-list="false"
                    action="https://up.qiniup.com"
                    :on-format-error="handleFormatError"
                    :on-progress="handleProgress"
                    :on-success="handleSuccess"
                    :on-error="handleError"
                    :format="['jpg', 'png', 'jpeg']"
                    :data="{token:upload_token}"
                    :before-upload="handleBeforeUpload"
                    style="float: left;">
              <Button
                  style="width:80px;height:30px;background:rgba(248,249,250,1);border:1px solid rgba(232,233,237,1);border-radius:2px;">
                上传文件
              </Button>
              <p style="color:#999;margin-top: 8px;">建议尺寸: 400*400px，JPG、PNG格式，图片不超过1M</p>
            </Upload>
          </div>
        </FormItem>
        <FormItem label="电话" prop="phone" class="label_required">
          <Input v-model="formValidate.phone" placeholder="请输入门店电话" />
        </FormItem>
        <FormItem label="所属地区" prop="area_id" class="label_required">
          <Cascader
              :data="area_list"
              v-model='area_value'
              @on-change='selectArea'
              placeholder="请选择地区"
              :load-data="loadData">
          </Cascader>
        </FormItem>
        <FormItem label="地址" prop="address" class="label_required">
          <Input v-model="formValidate.address" placeholder="请输入门店地址" />
        </FormItem>
        <FormItem label="服务时间" prop="service_time" class="label_required">
          <Input v-model="formValidate.service_time" placeholder="请输入门店服务时间" />
        </FormItem>
        <FormItem label="平台佣金比例(%)" prop="commission_pre" class="label_required">
          <Input v-model="formValidate.commission_pre" placeholder="百分制；例如：1代表1%" style="width: 100%"
                 min="0.01" />
        </FormItem>
      </Form>
      <div class="btns">
        <Button :loading="isSubmitting" type="primary" @click="handleSubmit">提交</Button>
      </div>
    </Modal>

    <Modal title="查看图片" v-model="visible">
      <img :src="imgName" v-if="visible" style="width: 100%">
    </Modal>
  </div>
</template>
<script>

import {
  getQiniu,
  childBtnPermission,
  shopList,
  editShop,
  changeShopStatus,
  areaList,
} from '@/api/main'

export default {
  data () {
    return {
      permissionList: [],
      isSubmitting: false,
      pagenation: {},
      columns: [
        {
          key: 'name',
          title: '名称',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.name)
          },
        },
        {
          key: 'sub_name',
          title: '简称',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.sub_name)
          },
        },
        {
          key: 'logo',
          title: 'logo',
          align: 'center',
          render: (h, params) => {
            return h(
                'div',
                {
                  style: {
                    backgroundImage: 'url(' + params.row.logo + ')',
                    width: '100px',
                    height: '100px',
                    objectFit: 'cover',
                    margin: '10px auto',
                    position: 'relative',
                    cursor: 'pointer',
                    backgroundSize: 'cover',
                  },
                  on: {
                    click: e => {
                    },
                  },
                }
            )
          },
        },
        {
          title: '电话',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.phone)
          },
        },
        {
          title: '门店地址',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.address)
          },
        },
        {
          title: '服务时间',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.service_time)
          },
        },
        {
          title: '平台佣金比例(%)',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.commission_pre)
          },
        },
        {
          key: 'status',
          title: '状态',
          align: 'center',
          render: (h, params) => h('i-switch', {
                props: {
                  value: params.row.status,
                  'true-value': 1,
                  'false-value': 0
                },
                style: {
                  width: '60px'
                },
                on: {
                  'on-change': () => {
                    let status = parseInt(params.row.status) ? 0 : 1
                    this.changeStatus(params.row.id, status)
                  }
                }
              }, [
                h('span', {
                  slot: 'open',
                  domProps: {
                    innerHTML: '启用'
                  }
                }),
                h('span', {
                  slot: 'close',
                  domProps: {
                    innerHTML: '禁用'
                  }
                })
              ]
          )
        },
        {
          title: '操作',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h(
                  'Button',
                  {
                    style: {
                      marginBottom: '5px',
                      marginRight: '5px',
                      border: 0,
                      background: 'transparent',
                      fontSize: '14px',
                      color: '#377EEF',
                      display: this.permissionList.indexOf('shop-edit') !== -1 ? 'inline-block' : 'none'
                    },
                    on: {
                      click: () => {
                        this.doEdit(params.row)
                      },
                    },
                  },
                  '编辑',
              ),
              h(
                  'Poptip',
                  {
                    props: {
                      confirm: true,
                      title: '您确定要删除该门店?',
                      transfer: true,
                    },
                    on: {
                      'on-ok': () => {
                        this.changeStatus(params.row.id, -1)
                      },
                    },
                  },
                  [
                    h(
                        'Button',
                        {
                          style: {
                            margin: '0 5px 5px 0',
                            border: 0,
                            background: 'transparent',
                            fontSize: '14px',
                            color: '#377EEF',
                            display: this.permissionList.indexOf('shop-delete') !== -1 ? 'inline-block' : 'none'
                          },
                          props: {
                            placement: 'top',
                          }
                        },
                        '删除',
                    ),
                  ],
              )
            ])
          },
        },
      ],
      showEditModal: false,
      list: [],
      loading: true,
      upload_token: '',
      visible: false,
      imgName: '',
      formValidate: {
        id: 0,
        name: '',
        sub_name: '',
        logo: '',
        phone: '',
        province_id: 0,
        city_id: 0,
        area_id: 0,
        address: '',
        service_time: '',
        commission_pre: '',
      },
      filter: {
        page: 0,
        page_size: 20,
        name: ''
      },
      tmp_area_list: [],
      area_list: [],
      area_value: [],
    }
  },
  watch: {},
  methods: {
    change: function (page) {
      this.loading = true
      this.filter.page = page - 1
      this.getList()
    },
    search: function () {
      this.filter.page = 0
      this.getList()
    },
    add: function () {
      this.formValidate.id = 0
      this.area_value = []
      this.showEditModal = true
      this.handleReset('formValidate')
      // this.resetFormValidate()
    },
    handleReset (name) {
      this.$refs[name].resetFields()
    },
    resetFormValidate () {
      this.formValidate.name = ''
      this.formValidate.logo = ''
    },
    doEdit: function (obj) {
      this.formValidate = Object.assign({}, obj)
      this.area_value = []
      this.area_value.push(obj.province_id, obj.city_id, obj.area_id)
      this.showEditModal = true
    },
    loadData (item, callback) {
      item.loading = true
      var area_data = this.tmp_area_list[item.index].children
      area_data.map(function (i) {
        var data = {}
        data.label = i.label
        data.value = i.value
        if (i.hasOwnProperty('children')) {
          data.children = i.children
        }
        item.children.push(data)
      })
      item.loading = false
      callback()
    },
    selectArea (value) {
      console.log(value)
      this.formValidate.province_id = value[0]
      this.formValidate.city_id = value[1]
      this.formValidate.area_id = value[2]
    },
    handleBeforeUpload (file) {
      if (file.size > 1024 * 1024) {
        this.$Message.error("图片不超过1M")
      }
    },
    handleSubmit () {
      let _this = this
      if (this.formValidate.name == '') {
        this.$Message.error("请输入门店名称");
        return;
      }
      if (this.formValidate.sub_name == '') {
        this.$Message.error("请输入门店简称");
        return;
      }
      if (this.formValidate.logo == '') {
        this.$Message.error("请上传门店logo");
        return;
      }
      if (this.formValidate.phone == '') {
        this.$Message.error("请输入门店电话");
        return;
      }
      if (this.formValidate.address == '') {
        this.$Message.error("请选择门店地区");
        return;
      }
      if (this.formValidate.address == '') {
        this.$Message.error("请输入门店地址");
        return;
      }
      if (this.formValidate.service_time == '') {
        this.$Message.error("请输入门店服务时间");
        return;
      }
      //console.log(this.formValidate); return false;

      if (this.isSubmitting) return
      this.isSubmitting = true

      editShop(this.formValidate).then(res => {
        if (res.code === 0) {
          this.$Message.success('操作成功')
          this.showEditModal = false
          this.search()
        } else {
          this.$Message.error(res.text)
        }
        setTimeout(() => this.isSubmitting = false, 1000)
      })
    },
    handleFormatError (file) {
      this.$Message.error('文件 ' + file.name + ' 格式不正确，请选择图片文件。')
    },
    handleProgress (event, file) { },
    handleSuccess (event, file, fileList) {
      this.formValidate.logo = file.response.domain + file.response.key
    },
    handleError (event, file) { },
    handleView (img_url) {
      this.imgName = img_url
      this.visible = true
    },
    handleRemove (index) {
      this.formValidate.logo = '';
    },
    formatJson (filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    exportData () {
      let _this = this
      _this.filter.page = 0
      _this.filter.page_size = 500
      _this.export_list = []
      _this.export()
    },
    export () {
      let _this = this
      shopList(this.filter).then(res => {
        if (res.code == 0) {
          if (res.data.length) {
            _this.export_list.push.apply(_this.export_list, res.data)
            _this.filter.page++
            setTimeout(() => {
              _this.export()
            }, 500)
          } else {
            _this.filter.page_size = 20
            const { export_json_to_excel } = require('../../excel/Export2Excel');
            const tHeader = ['名称', '简称', '电话', '地址', '服务时间'];
            const filterVal = ['name', 'sub_name', 'phone', 'address', 'service_time'];
            const data = _this.formatJson(filterVal, _this.export_list)
            export_json_to_excel(tHeader, data, '门店信息')
          }
        }
      })
    },
    async initQn () {
      let qiniu = await getQiniu()
      this.upload_token = qiniu.token
    },
    getPermissionList (parent_name) {
      childBtnPermission({ parent_name }).then(res => {
        if (res.code === 0) {
          this.permissionList = res.data
        }
      })
    },
    getList () {
      shopList(this.filter).then(res => {
        if (res.code == 0) {
          this.list = res.data
          this.loading = false
          this.pagenation.currentPage = parseInt(res.currentPage) + 1
          this.pagenation.totalPage = parseInt(res.totalPage)
          this.pagenation.perPage = parseInt(res.perPage)
        }
      })
    },
    changeStatus (id, status) {
      changeShopStatus({
        id,
        status
      }).then(res => {
        if (res.code === 0) {
          this.$Message.success('操作成功')
          this.search()
        } else {
          this.$Message.error(res.text)
        }
      })
    },
  },
  mounted () {
    this.initQn();
    this.getPermissionList('shop-list')
    this.getList()


    areaList().then(res => {
      if (res.code == 0) {
        if (res.code == 0) {
          var tmp_area = []
          res.data.map(function (i, index) {
            var data = {}
            data.index = index
            data.label = i.label
            data.value = i.value
            data.children = []
            data.loading = false
            tmp_area.push(data)
          })
          this.tmp_area_list = res.data
          this.area_list = tmp_area
        }
      }
    })
  }
}
</script>
<style>
</style>
<style scoped lang="less">

</style>
